import { sendMessage } from 'webext-bridge/popup'
import type { ExtensionAuthState } from '~/types/auth'

// 认证相关的API工具
export class AuthenticatedApiClient {
  private baseUrl: string
  private authState: ExtensionAuthState | null = null

  constructor(baseUrl: string = '') {
    this.baseUrl = baseUrl
  }

  // 获取当前认证状态
  private async getAuthState(): Promise<ExtensionAuthState | null> {
    try {
      const authState = await sendMessage('get-auth-state', {}, 'background')
      this.authState = authState as ExtensionAuthState | null
      return this.authState
    }
    catch (error) {
      console.error('获取认证状态失败:', error)
      return null
    }
  }

  // 获取认证头
  private async getAuthHeaders(): Promise<Record<string, string>> {
    const authState = await this.getAuthState()
    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
    }

    if (authState?.isAuthenticated && authState.token) {
      headers.Authorization = `Bearer ${authState.token}`
    }

    return headers
  }

  // 检查认证状态
  public async isAuthenticated(): Promise<boolean> {
    const authState = await this.getAuthState()
    return authState?.isAuthenticated === true
  }

  // 通用的认证请求方法
  private async authenticatedRequest(
    url: string,
    options: RequestInit = {},
  ): Promise<Response> {
    const authHeaders = await this.getAuthHeaders()

    const finalOptions: RequestInit = {
      ...options,
      headers: {
        ...authHeaders,
        ...options.headers,
      },
    }

    const fullUrl = url.startsWith('http') ? url : `${this.baseUrl}${url}`

    try {
      const response = await fetch(fullUrl, finalOptions)

      // 如果是401未授权，可能需要重新同步认证状态
      if (response.status === 401) {
        console.warn('API请求未授权，可能需要重新登录')
        // 触发认证状态刷新
        await sendMessage('refresh-auth-state', {}, 'background')
      }

      // 参数验证返回 http 为 422 则提示错误信息
      if (response.status === 422) {
        const errorData = await response.json()
        throw new Error(errorData.message)
      }

      return response
    }
    catch (error) {
      console.error('API请求失败:', error)
      throw error
    }
  }

  // GET 请求
  public async get(url: string, options: RequestInit = {}): Promise<Response> {
    return this.authenticatedRequest(url, {
      ...options,
      method: 'GET',
    })
  }

  // POST 请求
  public async post(url: string, data?: any, options: RequestInit = {}): Promise<Response> {
    return this.authenticatedRequest(url, {
      ...options,
      method: 'POST',
      body: data ? JSON.stringify(data) : undefined,
    })
  }

  // PUT 请求
  public async put(url: string, data?: any, options: RequestInit = {}): Promise<Response> {
    return this.authenticatedRequest(url, {
      ...options,
      method: 'PUT',
      body: data ? JSON.stringify(data) : undefined,
    })
  }

  // DELETE 请求
  public async delete(url: string, options: RequestInit = {}): Promise<Response> {
    return this.authenticatedRequest(url, {
      ...options,
      method: 'DELETE',
    })
  }

  // 举报相关的API方法
  public async submitReport(data: {
    channelId: string
    reason: string
    description?: string
    isAnonymous?: boolean
  }): Promise<any> {
    const response = await this.post('/api/reports', data)
    return response.json()
  }

  // 获取举报记录
  public async getReports(platformUserId?: string): Promise<any> {
    const url = platformUserId ? `/api/reports?platform_user_id=${encodeURIComponent(platformUserId)}` : '/api/reports'
    const response = await this.get(url)
    return response.json()
  }

  // 获取频道举报状态
  public async getChannelReportStatus(channelId: string): Promise<any> {
    const response = await this.get(`/api/channels/${channelId}/report-status`)
    return response.json()
  }
}

// 创建默认实例
export const apiClient = new AuthenticatedApiClient()

// 导出便捷方法
export const reportApi = {
  // 提交举报
  submit: (data: {
    channelId: string
    reason: string
    description?: string
    isAnonymous?: boolean
  }) => apiClient.submitReport(data),

  // 获取举报记录
  getList: (platformUserId?: string) => apiClient.getReports(platformUserId),

  // 获取频道状态
  getChannelStatus: (channelId: string) => apiClient.getChannelReportStatus(channelId),
}
